package org.cjlm.ui.template;

import org.cjlm.ui.pub.HeadItem;
import org.cjlm.ui.pub.MButton;
import org.cjlm.ui.pub.MTabbedPane;
import org.cjlm.ui.pub.MTable;
import org.cjlm.vo.SuperVO;
import org.cjlm.vo.template.TemplateAVO;
import org.cjlm.vo.template.TemplateActionVO;
import org.cjlm.vo.template.TemplateBVO;
import org.cjlm.vo.template.TemplateMVO;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BillCardPanel extends JPanel {
    private TemplateMVO mvo;
    private MTabbedPane detailTabs = new MTabbedPane();
    private Map<String, MTable> bodyTableMap = new HashMap<>();
    private Map<String, DefaultTableModel> bodyModelMap = new HashMap<>();
    private final List<MButton> buttons = new ArrayList<>();
    private boolean isedit = false;//非编辑态
    private Map<String, HeadItem> cardFields = new HashMap<>(); // 新增：存储主表字段
    public BillCardPanel(TemplateMVO mvo) {
        super();
        this.mvo = mvo;
        initUI();
        refreshEditState(); // 初始化时设置编辑状态
    }

    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        // 主表详情区域
        JPanel headPanel = createHeadPanel();
        // 子表层叠面板（与列表界面相同实例）
        initBodyTable();
        // 组装卡片界面
        JSplitPane splitPane = new JSplitPane(
                JSplitPane.VERTICAL_SPLIT,
                headPanel,
                detailTabs
        );
        splitPane.setResizeWeight(0.6);  // 60%空间给主表，40%给子表
        splitPane.setOneTouchExpandable(true);  // 添加快速折叠按钮

        add(createBtnPanel(),  BorderLayout.NORTH);
        add(splitPane,  BorderLayout.CENTER); // 将分割窗格放入CENTER
    }

    private JPanel createHeadPanel() {
        String title = null;
        JPanel headPanel = new JPanel();
        headPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));
        if(this.mvo != null){
            List<TemplateBVO> fieldvolist = new ArrayList<>();
            List<SuperVO> avolist = this.mvo.getChildren();
            for(SuperVO avol : avolist) {
                TemplateAVO avo = (TemplateAVO) avol;
                if (avo.getType() == 1 && avo.getIszb()) {
                    List<SuperVO> bvolist = avo.getChildren(TemplateBVO.class.getName());
                    for(SuperVO bvol : bvolist){
                        TemplateBVO bvo = (TemplateBVO) bvol;
                        fieldvolist.add(bvo);
                    }
                    title = avo.getName();
                    break;
                }
            }

            this.cardFields  = new HashMap<>(); // 初始化
            headPanel.setBorder(BorderFactory.createTitledBorder(title));

            for (TemplateBVO fieldvo : fieldvolist) {
                HeadItem item = new HeadItem(fieldvo.getCode(), fieldvo.getName());
                item.setEditable(isedit);
                item.setTxtBackground(isedit  ? Color.WHITE : new Color(240, 240, 240));
                headPanel.add(item);
                cardFields.put(fieldvo.getCode(), item);
            }
        }
        return headPanel;
    }

    private void initBodyTable() {
        // 子表层叠面板
        detailTabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

        if(this.mvo != null){
            List<SuperVO> avolist = this.mvo.getChildren();
            int index = 0;
            for(SuperVO avol : avolist) {
                TemplateAVO avo = (TemplateAVO) avol;
                if (avo.getType() == 1 && !avo.getIszb()) {//子表
                    List<String> columnlist = new ArrayList<>();
                    List<SuperVO> bvolist = avo.getChildren(TemplateBVO.class.getName());
                    if(bvolist != null){
                        for(SuperVO bvol : bvolist){
                            TemplateBVO bvo = (TemplateBVO) bvol;
                            columnlist.add(bvo.getName());
                        }
                    }
                    String[] columns = new String[columnlist.size()]; columnlist.toArray(columns);
                    DefaultTableModel bodyModel = new DefaultTableModel(columns, 0);
                    this.bodyModelMap.put(avo.getCode(), bodyModel);
                    MTable bodyTable = new MTable(bodyModel);
                    bodyTable.addKeyListener(new KeyAdapter() {
                        @Override
                        public void keyPressed(KeyEvent e) {
                            if(e.getKeyCode() == KeyEvent.VK_DELETE){
                                deleteLine();
                            }
                        }
                    });
                    this.bodyTableMap.put(avo.getCode(), bodyTable);
                    detailTabs.addTab(avo.getCode(), avo.getName(), new JScrollPane(bodyTable), index ++);
                }
            }
        }
    }

    private JPanel createBtnPanel() {
        if(this.mvo != null){
            List<SuperVO> avolist = this.mvo.getChildren();
            for(SuperVO avol : avolist){
                TemplateAVO avo = (TemplateAVO) avol;
                if(avo.getType() == 1 && avo.getIszb()){
                    List<SuperVO> actionlist = avo.getChildren(TemplateActionVO.class.getName());
                    for(SuperVO actionvo : actionlist){
                        TemplateActionVO action = (TemplateActionVO)actionvo;
                        if(action.getCardlist() == 1 || action.getCardlist() == 3){
                            this.buttons.add(new MButton(action.getCode(), action.getName(), action.getActiontype(), action.getIsedit() == 1 ? true : false));
                        }
                    }
                    break;
                }
            }
        }
        //显示按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        for(MButton button : this.buttons){
            buttonPanel.add(button);
        }

        return buttonPanel;
    }

    public void refreshButtonState() {
        for (MButton button : buttons) {
            if(isedit){
                button.setEnabled(button.isIsedit());
            }else{
                button.setEnabled(!button.isIsedit());
            }

        }
    }

    // 新增：统一刷新编辑状态的方法
    public void refreshEditState() {
        // 2. 控制主表字段编辑性
        for (HeadItem item : cardFields.values())  {
            item.setEditable(isedit);
            item.setTxtBackground(isedit  ? Color.WHITE : new Color(240, 240, 240)); // 视觉提示
        }

        // 3. 控制子表编辑性
        for (JTable table : bodyTableMap.values())  {
            // 如果需要单元格级控制
             table.setDefaultEditor(Object.class,  isedit ? new DefaultCellEditor(new JTextField()) : null);
        }
        refreshButtonState();
    }

    // 新增：设置编辑状态的外部接口
    public void setEditMode(boolean isedit) {
        this.isedit  = isedit;
        refreshEditState();
    }

    public List<MButton> getButtons() {
        return buttons;
    }

    public DefaultTableModel getBillModel(){
        return getBillModel(this.detailTabs.getSelectTablecode());
    }

    public DefaultTableModel getBillModel(String tablecode){
        return this.bodyModelMap.get(tablecode);
    }

    public MTable getBillTable(){
        return this.bodyTableMap.get(this.detailTabs.getSelectTablecode());
    }

    public MTable getBillTable(String tablecode){
        return this.bodyTableMap.get(tablecode);
    }

    public void addNewLine(){
        if(this.isedit){
            DefaultTableModel model = getBillModel();
            MTable table = getBillTable();
            // 添加新行
            model.addRow(new Object[0]);
            int newRowIndex = model.getRowCount()  - 1;  // 新增行索引

            // 设置选中新增行（确保在Swing事件线程中执行）
            SwingUtilities.invokeLater(()  -> {
                // 设置选中状态
                table.setRowSelectionInterval(newRowIndex,  newRowIndex);

                // 滚动到新增行位置
                Rectangle cellRect = table.getCellRect(newRowIndex,  0, true);
                table.scrollRectToVisible(cellRect);

                // 请求焦点确保立即生效
                table.requestFocusInWindow();
            });
        }
    }

    public void deleteLine(){
        if(this.isedit){
            DefaultTableModel model = getBillModel();
            MTable table = getBillTable();
            int[] selrows = table.getSelectedRows();
            int option = JOptionPane.showConfirmDialog(this,
                    "确定删除选中的 " + selrows.length  + " 行数据？",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION);

            if (option != JOptionPane.YES_OPTION) {
                return; // 用户取消删除
            }
            if(selrows != null && selrows.length > 0){
                // 记录删除前最小选中行索引
                int minSelectedRow = selrows[0];
                // 倒序删除行
                for (int i = selrows.length  - 1; i >= 0; i--) {
                    model.removeRow(selrows[i]);
                }

                // 计算新选中行索引
                int newSelectedRow;
                int rowCount = model.getRowCount();
                if (rowCount > 0) {
                    if (minSelectedRow > 0) {
                        // 优先选中被删行的上一行
                        newSelectedRow = minSelectedRow - 1;
                    } else if (minSelectedRow < rowCount) {
                        // 若首行被删，则选中原位置行（现为新首行）
                        newSelectedRow = minSelectedRow;
                    } else {
                        // 特殊情况：删除最后一行时选中新最后一行
                        newSelectedRow = rowCount - 1;
                    }
                } else {
                    newSelectedRow = -1;
                }

                // 设置选中状态
                if (newSelectedRow >= 0) {
                    SwingUtilities.invokeLater(()  -> {
                        table.setRowSelectionInterval(newSelectedRow,  newSelectedRow);
                        Rectangle rect = table.getCellRect(newSelectedRow,  0, true);
                        table.scrollRectToVisible(rect);
                        table.requestFocusInWindow();
                    });
                }
            }
        }
    }
}
